package com.lanou.userLogin.user.dao;

import com.lanou.userLogin.user.domain.User;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserRegisterDaoImpl implements UserRegisterDao {

    private ComboPooledDataSource dataSource = new ComboPooledDataSource();

    @Override
    public List<User> findByUsername(String username) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            List<User> user = (List) qr.query(conn, "select * from tb_user where username = ?", new BeanListHandler<User>(User.class), username);
            System.out.println("-------------" + user);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public List<User> findByEmail(String email) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            List<User> user = qr.query(conn, "select * from tb_user where email = ?", new BeanListHandler<User>(User.class), email);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public int add(User form) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            int result = qr.update(conn, "insert into tb_user(uid,username,password,email,code) values (?,?,?,?,?)", form.getUid(),form.getUsername(), form.getPassword(), form.getEmail(),form.getCode());
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
